package com.ruoyi.system.controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.service.OssService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Product;
import com.ruoyi.system.service.IProductService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;

/**
 * 商品管理Controller
 * 
 * @author Amanda
 * @date 2025-07-15
 */
@RestController
@RequestMapping("/system/product")
public class ProductController extends BaseController
{
    @Autowired
    private IProductService productService;

    @Autowired
    private OssService ossService;

    /**
     * 查询商品管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:product:list')")
    @GetMapping("/list")
    public TableDataInfo list(Product product)
    {
        startPage();
        List<Product> list = productService.selectProductList(product);
        return getDataTable(list);
    }

    /**
     * 导出商品管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:product:export')")
    @Log(title = "商品管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Product product)
    {
        List<Product> list = productService.selectProductList(product);
        ExcelUtil<Product> util = new ExcelUtil<Product>(Product.class);
        util.exportExcel(response, list, "商品管理数据");
    }

    /**
     * 获取商品管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:product:query')")
    @GetMapping(value = "/{productId}")
    public AjaxResult getInfo(@PathVariable("productId") Long productId)
    {
        Product product = productService.selectProductByProductId(productId);
        // 核心：反转义数据库存储的内容
        String content = product.getProductContent();
        String rawHtml = (content != null)
                ? HtmlUtils.htmlUnescape(content)
                : "";  // 返回空字符串而非null

        product.setProductContent(rawHtml);

        return AjaxResult.success(product);
    }

    /**
     * 新增商品管理
     */
    @PreAuthorize("@ss.hasPermi('system:product:add')")
    @Log(title = "商品管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Product product)
    {
        // 富文本转义
        String safeContent = HtmlUtils.htmlEscape(product.getProductContent());
        product.setProductContent(safeContent);

        product.setProductAddtime(LocalDateTime.now());
        return toAjax(productService.insertProduct(product));
    }

    /**
     * 修改商品管理
     */
    @PreAuthorize("@ss.hasPermi('system:product:edit')")
    @Log(title = "商品管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Product product)
    {
        // 富文本转义
        String safeContent = HtmlUtils.htmlEscape(product.getProductContent());
        product.setProductContent(safeContent);

        return toAjax(productService.updateProduct(product));
    }

    /**
     * 删除商品管理
     */
    @PreAuthorize("@ss.hasPermi('system:product:remove')")
    @Log(title = "商品管理", businessType = BusinessType.DELETE)
	  @DeleteMapping("/{productIds}")
    public AjaxResult remove(@PathVariable Long[] productIds)
    {
        return toAjax(productService.deleteProductByProductIds(productIds));
    }


    /**
     * 上传商品图片
     */
    @PostMapping("/upload")
    public AjaxResult upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam Long productId) {
        try {
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件不能为空");
            }

            // 上传到OSS并获取URL
            String fileUrl = ossService.addHeadImage(file);

            // 更新商品图片信息
            Product product = new Product();
            product.setProductId(productId);
            product.setProductPhoto(fileUrl);
            productService.updateProduct(product);

            return AjaxResult.success("上传成功", fileUrl);
        } catch (Exception e) {
            logger.error("上传商品图片失败", e);
            return AjaxResult.error("上传失败: " + e.getMessage());
        }
    }

}
